package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断传进来的是否为空
        if(loginDto!=null&&StringUtils.isNotBlank(loginDto.getPhone())&&StringUtils.isNotBlank(loginDto.getPassword())){
           //数据不为空   查询用户
            LambdaQueryWrapper<ApUser> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser user = getOne(wrapper);


            if (user==null){
                //用户不存在,返回响应
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //用户存在
                //核对密码
                    //获得盐
            String salt = user.getSalt();
            String password = loginDto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!password.equals(user.getPassword())){
                //密码不对，返回响应
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回token
            Map<String,Object> map=new HashMap<>();
            String token = AppJwtUtil.getToken(user.getId().longValue());
            map.put("token",token);
            user.setSalt("");
            user.setPassword("");
            map.put("user",user);
            return ResponseResult.okResult(map);
        }else{
            //游客登录  返回token id = 0
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map=new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 根据用户id查询用户
     * @param userId
     * @return
     */
    @Override
    public ResponseResult selectUser(Integer userId) {
        ApUser apUser = getById(userId);
        if (apUser!=null){
            return ResponseResult.okResult(apUser.getName());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
